#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

class Solution
{
public:
    string reverseWords(string s)
    {
        vector<char> sv;
        char lastChar = ' ';
        for (const char c : s)
        {
            if (c != ' ' || lastChar != ' ')
                sv.push_back(c);
            lastChar = c;
        }
        if (sv[sv.size() - 1] == ' ')
            sv.pop_back();
        reverse(sv.begin(), sv.end());
        int start = 0;
        for (int i = 0; i < sv.size(); i++)
        {
            if (sv[i] == ' ')
            {
                reverse(sv.begin() + start, sv.begin() + i);
                start = i + 1;
            }
        }
        reverse(sv.begin() + start, sv.end());
        return string(sv.begin(), sv.end());
    }
};

int main()
{
    cout << "Code151" << endl;
    Solution s;
    string ss = "  1qqqq2  1www2  ";
    cout << s.reverseWords(ss);
    return 0;
}